package com.xinzhidi.web.equipment.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xinzhidi.common.annotation.Log;
import com.xinzhidi.common.core.controller.BaseController;
import com.xinzhidi.common.core.domain.AjaxResult;
import com.xinzhidi.common.core.domain.R;
import com.xinzhidi.common.core.page.TableDataInfo;
import com.xinzhidi.common.enums.BusinessType;
import com.xinzhidi.common.utils.poi.ExcelUtil;
import com.xinzhidi.web.equipment.domain.Equipment;
import com.xinzhidi.web.equipment.domain.dto.*;
import com.xinzhidi.web.equipment.domain.vo.EquipmentImportVo;
import com.xinzhidi.web.equipment.domain.vo.EquipmentListVo;
import com.xinzhidi.web.equipment.dto.EquipmentGroupInfoDto;
import com.xinzhidi.web.equipment.service.EquipmentService;
import com.xinzhidi.web.house.domain.vo.HouseholdExcelVo;
import com.xinzhidi.web.house.service.IHouseholdService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 设备Controller
 *
 * @author ruoyi
 * @date 2023-05-29
 */
@RestController
@Api(tags = "设备")
@RequestMapping("/equipmentMessage")
@RequiredArgsConstructor
public class EquipmentController extends BaseController {

    private final EquipmentService equipmentService;


    private final IHouseholdService householdService;

    @ApiOperation("查询设备列表")
    @PreAuthorize("@ss.hasPermi('equipmentMessage:equipmentMessage:list')")
    @PostMapping("/listEquipment")
    public TableDataInfo<EquipmentListVo> listEquipment(@Validated @RequestBody EquipmentListDto dto) {
        startPagePost(dto);
        return equipmentService.selectEquipmentList(dto);
    }


    @ApiOperation(value = "查询设备列表(不分页)" ,notes = "协议获取设备使用，不带小区权限，否则定时任务获取当前用户会报错")
    @PostMapping("/listEquipmentNoPage")
    public List<EquipmentListVo> listEquipmentNoPage(@Validated @RequestBody EquipmentDto dto) {
        return equipmentService.listEquipmentNoPage(dto);
    }

    @ApiOperation("设备分组详情")
    @PreAuthorize("@ss.hasPermi('equipmentMessage:equipmentMessage:list')")
    @PostMapping("/equipmentGroupInfo")
    public TableDataInfo<EquipmentListVo> equipmentGroupInfo(@Validated @RequestBody EquipmentGroupInfoDto dto) {
        startPagePost(dto);
        return equipmentService.equipmentGroupInfo(dto);
    }

    @ApiOperation("移除分组")
    @PreAuthorize("@ss.hasPermi('equipmentMessage:equipmentMessage:remove')")
    @GetMapping("/removeGroup")
    public R removeGroup(Integer equipmentId) {
         equipmentService.removeGroup(equipmentId);
         return R.ok();
    }

    @ApiOperation("导出设备列表")
    @PreAuthorize("@ss.hasPermi('equipmentMessage:equipmentMessage:export')")
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @PostMapping("/exportEquipment")
    public void exportEquipment(HttpServletResponse response, EquipmentListDto dto) {
        TableDataInfo<EquipmentListVo> list = equipmentService.selectEquipmentList(dto);
        ExcelUtil<EquipmentListVo> util = new ExcelUtil<EquipmentListVo>(EquipmentListVo.class);
        util.exportExcel(response, list.getRows(), "设备数据");
    }

    @ApiOperation("导出设备模版")
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        equipmentService.setBox();
        ExcelUtil<EquipmentImportVo> util = new ExcelUtil(EquipmentImportVo.class);
        util.importTemplateExcel(response, "设备数据");
    }


    @Log(title = "导入设备", businessType = BusinessType.IMPORT)
    @ApiOperation("导入设备")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<HouseholdExcelVo> util = new ExcelUtil(HouseholdExcelVo.class);
        List<HouseholdExcelVo> equipmentList = util.importExcel(file.getInputStream());
        String message = equipmentService.importEquipment(equipmentList);
        return success(message);
    }

    @ApiOperation("获取设备详细信息")
    @PreAuthorize("@ss.hasPermi('equipmentMessage:equipmentMessage:query')")
    @GetMapping(value = "/getEquipmentById")
    public R<EquipmentListVo> getEquipmentById(@RequestParam("id") Long id) {
        return R.ok(equipmentService.selectEquipmentById(id));
    }

    @ApiOperation("新增设备")
    @PreAuthorize("@ss.hasPermi('equipmentMessage:equipmentMessage:add')")
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @PostMapping("addEquipment")
    public AjaxResult addEquipment(@Validated @RequestBody EquipmentAddDto dto) {
        return toAjax(equipmentService.insertEquipment(dto));
    }

    @ApiOperation("修改设备")
    @PreAuthorize("@ss.hasPermi('equipmentMessage:equipmentMessage:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PostMapping("editEquipment")
    public AjaxResult editEquipment(@Validated @RequestBody EquipmentUpdDto dto) {
        return toAjax(equipmentService.updateEquipment(dto));
    }

    @ApiOperation("删除设备")
    @PreAuthorize("@ss.hasPermi('equipmentMessage:equipmentMessage:remove')")
    @Log(title = "设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/delEquipment")
    public AjaxResult delEquipment(@RequestParam Long[] ids) {
        return toAjax(equipmentService.deleteEquipmentByIds(ids));
    }


    @ApiOperation("批量分组")
    @PostMapping("setGroupByIds")
    public R setGroupByIds(@Validated @RequestBody SetGroupByIdDto dto) {
        Set<Long> collect = equipmentService.list(new LambdaQueryWrapper<>(Equipment.class).in(Equipment::getId, dto.getIds())).stream().map(Equipment::getLotId).collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(collect) || collect.size() > 1) {
            return R.fail("只能对同一小区数据进行批量分组");
        }
        equipmentService.update(new LambdaUpdateWrapper<>(Equipment.class).set(Equipment::getEquipmentGroupId, dto.getEquipmentGroupId()).in(Equipment::getId, dto.getIds()));
        return R.ok();
    }


}
